package jam4j.lang;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import java_cup.runtime.Symbol;

final class ParserRunner {
    private ParserRunner() { }

    static JamFile parse(String filename)
            throws IOException, ParseException {
        return parse(new FileInputStream(filename), filename);
    }
    
    static JamFile parseResource(String name)
            throws IOException, ParseException {
        return parseResource(name, name);
    }

    static JamFile parseResource(String name, String displayName)
            throws IOException, ParseException {
        return parse(ParserRunner.class.getResourceAsStream(name),
                displayName);
    }
    
    static JamFile parse(InputStream input, String filename)
            throws IOException, ParseException {
        final Lexer lexer = new Lexer(input, filename);
        final Parser parser = new Parser(lexer, lexer.symbolFactory());
        
        final Symbol symbol;
        try {
            symbol = parser.parse();
        } catch (IOException e) {
            throw e;
        } catch (ParseException e) {
            throw e;
        } catch (Exception e) {
            throw new ParseException(e);
        }
        
        return (JamFile) symbol.value;
    }
}